/*******************************************************************************
 * Copyright (c) 2010 by Thomas Jahn
 * This content is released under the MIT License. (Just like Flixel)
 * For questions mail me at lithander@gmx.de!
 ******************************************************************************/
package net.pixelpracht.tmx 
{
	import flash.display.BitmapData;
	import flash.geom.Rectangle;
	
	import starling.textures.Texture;
	import starling.textures.TextureAtlas;

	public class TmxTileSet
	{
		private var _tileProps:Array = [];
		private var _textureAtlas:TextureAtlas;
		
		public var map:TmxMap;
		
		public var firstGID:int = 0;
		public var source:String;
		public var name:String;
		public var tileWidth:int;
		public var tileHeight:int;
		public var spacing:int;
		public var margin:int;
		
		public var tileOffset:TmxTileOffset;
		public var image:TmxImage;
		
		//available only after immage has been assigned:
		public var numTiles:int = 0xFFFFFF;
		public var numRows:int = 1;
		public var numCols:int = 1;
		
		public function TmxTileSet(tileset:XML, parent:TmxMap) {
			map = parent;
			
			firstGID = tileset.@firstgid;
			source = tileset.hasOwnProperty("@source") ? tileset.@source : null;
			name = tileset.@name;
			tileWidth = tileset.@tilewidth;
			tileHeight = tileset.@tileheight;
			spacing = tileset.@spacing;
			margin = tileset.@margin;
			
			tileOffset = new TmxTileOffset(tileset.tileoffset[0]);
			image = new TmxImage(tileset.image[0]);
			
			//read properties
			for each(var node:XML in tileset.tile)
				if(node.properties[0])
					_tileProps[int(node.@id)] = new TmxPropertySet(node.properties[0]);
		}
		
		public function get textureAtlas():TextureAtlas {
			return _textureAtlas;
		}
		
		public function set associatedImage(v:BitmapData):void {
			var id:int = firstGID;
			_textureAtlas = new TextureAtlas(Texture.fromBitmapData(v), null);
			numCols = image.width/tileWidth;
			numRows = image.height/tileHeight;
			numTiles = numCols*numRows;
			for (var row:int = 0; row < numRows; row++) {
				for (var column:int = 0; column < numCols; column++) {
					var rect:Rectangle = new Rectangle(column * tileWidth, row * tileHeight, tileWidth, tileHeight);
					_textureAtlas.addRegion(id.toString(), rect);
					id++;
				}
			}
		}
		
		public function hasGid(gid:int):Boolean {
			return (gid >= firstGID) && (gid < firstGID + numTiles);
		}
		
		public function fromGid(gid:int):int {
			return gid - firstGID;
		}
		
		public function toGid(id:int):int {
			return firstGID + id;
		}

		public function getPropertiesByGid(gid:int):TmxPropertySet {
			return _tileProps[gid - firstGID];	
		}
		
		public function getProperties(id:int):TmxPropertySet {
			return _tileProps[id];	
		}
	}
}